// wind_speed_monitor/frontend/js/charts.js
document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表容器
    const chartContainers = {
        history: document.getElementById('history-chart'),
        forecast: document.getElementById('forecast-chart'),
        comparison: document.getElementById('comparison-chart'),
        distribution: document.getElementById('distribution-chart')
    };

    // 图表实例存储
    const chartInstances = {};
    
    // 图表配置
    const chartConfig = {
        timeRange: '24h',
        thresholdValue: 12.0,
        refreshInterval: 30000,
        activeStations: []
    };

    // 初始化所有图表
    function initCharts() {
        // 历史数据图表
        if (chartContainers.history) {
            chartInstances.history = createChart(
                chartContainers.history.getContext('2d'), 
                'line',
                { datasets: [] }, 
                getChartOptions('历史风速数据 (m/s)')
            );
        }

        // 预测数据图表
        if (chartContainers.forecast) {
            chartInstances.forecast = createChart(
                chartContainers.forecast.getContext('2d'), 
                'line',
                { datasets: [] }, 
                getChartOptions('风速预测 (m/s)')
            );
        }

        // 对比图表
        if (chartContainers.comparison) {
            chartInstances.comparison = createChart(
                chartContainers.comparison.getContext('2d'), 
                'line',
                { datasets: [] }, 
                getChartOptions('多站点风速对比 (m/s)')
            );
        }
        
        // 分布图表
        if (chartContainers.distribution) {
            chartInstances.distribution = createChart(
                chartContainers.distribution.getContext('2d'), 
                'bar',
                { datasets: [] }, 
                getDistributionChartOptions('风速分布 (m/s)')
            );
        }
    }
    
    // 创建图表辅助函数
    function createChart(ctx, type, data, options) {
        return new Chart(ctx, {
            type: type,
            data: data,
            options: options
        });
    }

    // 获取图表配置
    function getChartOptions(title) {
        return {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                title: {
                    display: true,
                    text: title,
                    color: 'rgba(255, 255, 255, 0.8)',
                    font: {
                        size: 16
                    }
                },
                legend: {
                    position: 'top',
                    labels: {
                        color: 'rgba(255, 255, 255, 0.7)'
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.7)'
                }
            },
            scales: {
                x: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.7)'
                    }
                },
                y: {
                    grid: {
                        color: 'rgba(255, 255, 255, 0.1)'
                    },
                    ticks: {
                        color: 'rgba(255, 255, 255, 0.7)'
                    },
                    beginAtZero: false
                }
            },
            interaction: {
                intersect: false,
                mode: 'nearest'
            }
        };
    }
    
    // 分布图表特殊配置
    function getDistributionChartOptions(title) {
        const baseOptions = getChartOptions(title);
        return {
            ...baseOptions,
            scales: {
                ...baseOptions.scales,
                y: {
                    ...baseOptions.scales.y,
                    beginAtZero: true
                }
            },
            plugins: {
                ...baseOptions.plugins,
                tooltip: {
                    ...baseOptions.plugins.tooltip,
                    callbacks: {
                        label: function(context) {
                            return `${context.dataset.label}: ${context.parsed.y}次`;
                        }
                    }
                }
            }
        };
    }

    // 格式化时间
    function formatTime(dateStr) {
        const date = new Date(dateStr);
        return `${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
    
    // 格式化日期时间
    function formatDateTime(dateStr) {
        const date = new Date(dateStr);
        return `${date.getMonth()+1}/${date.getDate()} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    }
    
    // 获取时间范围对应的小时数
    function getHoursFromRange(range) {
        switch(range) {
            case '1h': return 1;
            case '24h': return 24;
            case '7d': return 168;
            case '30d': return 720;
            default: return 24;
        }
    }

    // 渲染历史图表
    async function renderHistoryChart(stationId, timeRange) {
        if (!chartInstances.history) return;
        
        try {
            const hours = getHoursFromRange(timeRange || chartConfig.timeRange);
            
            // 尝试使用app.js提供的API获取数据
            let data;
            if (window.app && window.app.getStationData) {
                data = window.app.getStationData(stationId);
                if (data.length === 0) {
                    // 如果没有数据，尝试直接从API获取
                    const response = await fetch(`http://127.0.0.1:5000/api/stations/${stationId}/data?hours=${hours}`);
                    const result = await response.json();
                    if (result.success) {
                        data = result.data;
                    }
                }
            } else {
                // 直接从API获取
                const response = await fetch(`http://127.0.0.1:5000/api/stations/${stationId}/data?hours=${hours}`);
                const result = await response.json();
                if (result.success) {
                    data = result.data;
                }
            }
            
            if (!data || data.length === 0) {
                console.error('获取历史数据失败');
                return;
            }
            
            // 截取所需时间范围的数据
            data = data.slice(-hours);
            
            // 准备图表数据
            const labels = data.map(item => formatDateTime(item.timestamp));
            const windData = data.map(item => item.windSpeed);
            
            // 获取阈值
            let threshold = 12.0;
            if (window.app && window.app.getCurrentThreshold) {
                threshold = window.app.getCurrentThreshold();
            }
            
            // 更新图表数据
            chartInstances.history.data.labels = labels;
            chartInstances.history.data.datasets = [
                {
                    label: '风速 (m/s)',
                    data: windData,
                    borderColor: '#3b82f6',
                    backgroundColor: 'rgba(59, 130, 246, 0.1)',
                    tension: 0.3,
                    fill: true
                },
                {
                    label: '阈值',
                    data: Array(labels.length).fill(threshold),
                    borderColor: 'rgba(239, 68, 68, 0.7)',
                    borderDash: [5, 5],
                    pointRadius: 0
                }
            ];
            
            // 更新图表
            chartInstances.history.update();
            
            return data;
        } catch (error) {
            console.error('渲染历史图表失败:', error);
            return null;
        }
    }

    // 渲染预测图表
    function renderForecastChart(stationId, historyData) {
        if (!chartInstances.forecast) return;
        
        try {
            if (!historyData || historyData.length === 0) {
                console.error('预测图表缺少历史数据');
                return;
            }
            
            // 获取最新数据点作为预测起点
            const latestData = historyData[historyData.length - 1];
            
            // 简单预测算法（实际应用中可能需要更复杂的算法）
            const forecastData = [];
            const forecastHours = 12;
            
            // 使用最近5个数据点的趋势来预测
            const recentPoints = historyData.slice(-5);
            const avgChange = recentPoints.length > 1 ? 
                (recentPoints[recentPoints.length-1].windSpeed - recentPoints[0].windSpeed) / (recentPoints.length - 1) : 
                0;
            
            // 使用趋势和随机波动生成预测
            for (let i = 1; i <= forecastHours; i++) {
                const timestamp = new Date(new Date(latestData.timestamp).getTime() + i * 3600000).toISOString();
                // 趋势 + 随机波动（波动范围随时间增加）
                const randomFactor = (Math.random() - 0.5) * (i * 0.2);
                const predictedWind = Math.max(0, latestData.windSpeed + (avgChange * i) + randomFactor);
                
                forecastData.push({
                    timestamp: timestamp,
                    windSpeed: predictedWind
                });
            }
            
            // 准备图表数据
            const labels = forecastData.map(item => formatTime(item.timestamp));
            const windData = forecastData.map(item => item.windSpeed);
            
            // 获取阈值
            let threshold = 12.0;
            if (window.app && window.app.getCurrentThreshold) {
                threshold = window.app.getCurrentThreshold();
            }
            
            // 更新图表数据
            chartInstances.forecast.data.labels = labels;
            chartInstances.forecast.data.datasets = [
                {
                    label: '预测风速 (m/s)',
                    data: windData,
                    borderColor: '#10b981',
                    backgroundColor: 'rgba(16, 185, 129, 0.1)',
                    tension: 0.3,
                    fill: true
                },
                {
                    label: '阈值',
                    data: Array(labels.length).fill(threshold),
                    borderColor: 'rgba(239, 68, 68, 0.7)',
                    borderDash: [5, 5],
                    pointRadius: 0
                }
            ];
            
            // 更新图表
            chartInstances.forecast.update();
            
            // 更新预测显示框（如果存在）
            updateForecastBoxes(forecastData);
            
            return forecastData;
        } catch (error) {
            console.error('渲染预测图表失败:', error);
            return null;
        }
    }
    
    // 更新预测显示框
    function updateForecastBoxes(forecastData) {
        if (!forecastData || forecastData.length === 0) return;
        
        const forecast3h = document.getElementById('forecast-3h');
        const forecast6h = document.getElementById('forecast-6h');
        const forecast12h = document.getElementById('forecast-12h');
        
        if (forecast3h && forecastData.length > 2) {
            forecast3h.textContent = forecastData[2].windSpeed.toFixed(1) + ' m/s';
        }
        
        if (forecast6h && forecastData.length > 5) {
            forecast6h.textContent = forecastData[5].windSpeed.toFixed(1) + ' m/s';
        }
        
        if (forecast12h && forecastData.length > 11) {
            forecast12h.textContent = forecastData[11].windSpeed.toFixed(1) + ' m/s';
        }
    }

    // 渲染对比图表
    async function renderComparisonChart(stationIds, hours) {
        if (!chartInstances.comparison) return;
        
        try {
            // 获取所有站点的数据
            let comparisonData;
            
            // 尝试使用app.js提供的API
            if (window.app && window.app.compareStations) {
                comparisonData = await window.app.compareStations(stationIds, hours);
            } else {
                // 直接从API获取
                const response = await fetch(`http://127.0.0.1:5000/api/comparison?stations=${stationIds.join(',')}&hours=${hours}`);
                const result = await response.json();
                if (result.success) {
                    comparisonData = result.data;
                }
            }
            
            if (!comparisonData) {
                console.error('获取对比数据失败');
                return;
            }
            
            // 准备数据集
            const datasets = [];
            let labels = [];
            
            // 第一个站点的时间标签将作为基准
            if (stationIds.length > 0 && comparisonData[stationIds[0]]) {
                const firstStationData = comparisonData[stationIds[0]];
                labels = firstStationData.map(item => formatDateTime(item.timestamp));
            }
            
            // 为每个站点创建数据集
            stationIds.forEach(stationId => {
                if (comparisonData[stationId]) {
                    datasets.push({
                        label: `站点${stationId} 风速`,
                        data: comparisonData[stationId].map(item => item.windSpeed),
                        borderColor: getStationColor(stationId),
                        backgroundColor: 'rgba(0, 0, 0, 0)',
                        tension: 0.3
                    });
                }
            });
            
            // 更新图表
            chartInstances.comparison.data.labels = labels;
            chartInstances.comparison.data.datasets = datasets;
            chartInstances.comparison.update();
            
            return comparisonData;
        } catch (error) {
            console.error('渲染对比图表失败:', error);
            return null;
        }
    }
    
    // 渲染分布图表
    function renderDistributionChart(stationId, historyData) {
        if (!chartInstances.distribution) return;
        
        try {
            if (!historyData || historyData.length === 0) {
                console.error('分布图表缺少历史数据');
                return;
            }
            
            // 创建风速分布统计
            const distribution = {};
            const bucketSize = 1; // 1 m/s的间隔
            
            // 计算分布
            historyData.forEach(item => {
                // 将风速向下取整到最近的bucketSize倍数
                const bucket = Math.floor(item.windSpeed / bucketSize) * bucketSize;
                const bucketLabel = `${bucket}-${bucket + bucketSize}`;
                
                if (!distribution[bucketLabel]) {
                    distribution[bucketLabel] = 0;
                }
                distribution[bucketLabel]++;
            });
            
            // 转换为数组并排序
            const sortedData = Object.entries(distribution)
                .map(([label, count]) => ({ label, count }))
                .sort((a, b) => {
                    const numA = parseFloat(a.label.split('-')[0]);
                    const numB = parseFloat(b.label.split('-')[0]);
                    return numA - numB;
                });
            
            // 准备图表数据
            const labels = sortedData.map(item => item.label);
            const counts = sortedData.map(item => item.count);
            
            // 获取阈值
            let threshold = 12.0;
            if (window.app && window.app.getCurrentThreshold) {
                threshold = window.app.getCurrentThreshold();
            }
            
            // 根据阈值确定颜色
            const backgroundColors = labels.map(label => {
                const minVal = parseFloat(label.split('-')[0]);
                return minVal >= threshold ? 'rgba(239, 68, 68, 0.6)' : 'rgba(59, 130, 246, 0.6)';
            });
            
            // 更新图表
            chartInstances.distribution.data.labels = labels;
            chartInstances.distribution.data.datasets = [{
                label: '风速分布',
                data: counts,
                backgroundColor: backgroundColors,
                borderColor: 'rgba(255, 255, 255, 0.2)',
                borderWidth: 1
            }];
            
            chartInstances.distribution.update();
        } catch (error) {
            console.error('渲染分布图表失败:', error);
        }
    }

    // 获取站点颜色
    function getStationColor(stationId) {
        const colors = {
            'A': '#3B82F6', // 蓝色
            'B': '#10B981', // 绿色
            'C': '#F59E0B', // 黄色
            'D': '#8B5CF6'  // 紫色
        };
        return colors[stationId] || '#6B7280';
    }

    // 更新所有图表
    async function updateAllCharts(stationId, timeRange) {
        if (!stationId) {
            // 如果没有提供站点ID，尝试从其他地方获取
            if (window.app && window.app.getCurrentStation) {
                stationId = window.app.getCurrentStation();
            } else {
                // 从URL获取站点ID
                const urlParams = new URLSearchParams(window.location.search);
                stationId = urlParams.get('id') || 'A';
            }
        }
        
        if (!timeRange) {
            timeRange = chartConfig.timeRange;
        }
        
        // 更新图表配置
        chartConfig.timeRange = timeRange;
        
        // 渲染历史图表，并使用返回的数据渲染其他图表
        const historyData = await renderHistoryChart(stationId, timeRange);
        if (historyData) {
            renderForecastChart(stationId, historyData);
            renderDistributionChart(stationId, historyData);
        }
        
        // 如果有多个站点需要对比
        if (chartConfig.activeStations.length > 0) {
            renderComparisonChart(
                [...chartConfig.activeStations, stationId].filter((v, i, a) => a.indexOf(v) === i), // 确保没有重复
                getHoursFromRange(timeRange)
            );
        }
    }

    // 设置WebSocket更新
    function setupChartUpdates() {
        // 如果全局socket可用，监听数据更新
        if (window.socket) {
            window.socket.on('data_update', function(updates) {
                // 获取当前站点
                let currentStationId;
                if (window.app && window.app.getCurrentStation) {
                    currentStationId = window.app.getCurrentStation();
                } else {
                    const urlParams = new URLSearchParams(window.location.search);
                    currentStationId = urlParams.get('id') || 'A';
                }
                
                // 如果更新包含当前站点，更新图表
                if (updates[currentStationId]) {
                    updateAllCharts(currentStationId, chartConfig.timeRange);
                }
            });
        }
        
        // 定时刷新图表
        setInterval(function() {
            // 获取当前站点
            let currentStationId;
            if (window.app && window.app.getCurrentStation) {
                currentStationId = window.app.getCurrentStation();
            } else {
                const urlParams = new URLSearchParams(window.location.search);
                currentStationId = urlParams.get('id') || 'A';
            }
            
            updateAllCharts(currentStationId, chartConfig.timeRange);
        }, chartConfig.refreshInterval);
    }

    // 添加站点进行对比
    function addStationForComparison(stationId) {
        if (!chartConfig.activeStations.includes(stationId)) {
            chartConfig.activeStations.push(stationId);
            
            // 如果有对比图表，更新它
            if (chartInstances.comparison) {
                const currentStationId = window.app ? window.app.getCurrentStation() : 'A';
                const allStations = [...chartConfig.activeStations, currentStationId].filter((v, i, a) => a.indexOf(v) === i);
                
                renderComparisonChart(
                    allStations,
                    getHoursFromRange(chartConfig.timeRange)
                );
            }
        }
    }

    // 移除对比站点
    function removeStationFromComparison(stationId) {
        const index = chartConfig.activeStations.indexOf(stationId);
        if (index !== -1) {
            chartConfig.activeStations.splice(index, 1);
            
            // 如果有对比图表，更新它
            if (chartInstances.comparison) {
                const currentStationId = window.app ? window.app.getCurrentStation() : 'A';
                const allStations = [...chartConfig.activeStations, currentStationId].filter((v, i, a) => a.indexOf(v) === i);
                
                renderComparisonChart(
                    allStations,
                    getHoursFromRange(chartConfig.timeRange)
                );
            }
        }
    }

    // 设置事件监听器
    function setupEventListeners() {
        // 时间范围选择变化
        const timeRangeSelect = document.getElementById('time-range');
        if (timeRangeSelect) {
            timeRangeSelect.addEventListener('change', function() {
                chartConfig.timeRange = this.value;
                
                // 获取当前站点
                let currentStationId;
                if (window.app && window.app.getCurrentStation) {
                    currentStationId = window.app.getCurrentStation();
                } else {
                    const urlParams = new URLSearchParams(window.location.search);
                    currentStationId = urlParams.get('id') || 'A';
                }
                
                updateAllCharts(currentStationId, chartConfig.timeRange);
            });
        }
        
        // 对比按钮点击
        const compareBtn = document.getElementById('compare-btn');
        if (compareBtn) {
            compareBtn.addEventListener('click', function() {
                const stations = window.app ? window.app.getAllStations() : ['A', 'B', 'C', 'D'];
                const currentStation = window.app ? window.app.getCurrentStation() : 'A';
                
                // 显示一个简单的模态对话框
                const stationsToCompare = stations.filter(id => id !== currentStation);
                
                // 假设在UI上显示一个选择对话框
                alert(`请在控制台中测试对比功能。可用站点：${stationsToCompare.join(', ')}`);
                console.log('使用charts.addStationForComparison("站点ID")添加站点进行对比');
                console.log('使用charts.removeStationFromComparison("站点ID")移除对比站点');
            });
        }
    }

    // 初始化
    function init() {
        initCharts();
        setupEventListeners();
        
        // 获取当前站点并加载数据
        let currentStationId;
        if (window.app && window.app.getCurrentStation) {
            currentStationId = window.app.getCurrentStation();
        } else {
            const urlParams = new URLSearchParams(window.location.search);
            currentStationId = urlParams.get('id') || 'A';
        }
        
        // 获取时间范围
        const timeRangeSelect = document.getElementById('time-range');
        if (timeRangeSelect) {
            chartConfig.timeRange = timeRangeSelect.value;
        }
        
        // 初始化图表
        updateAllCharts(currentStationId, chartConfig.timeRange);
        
        // 设置自动更新
        setupChartUpdates();
    }
    
    // 调用初始化
    init();
    
    // 暴露公共方法
    window.charts = {
        updateCharts: updateAllCharts,
        addStationForComparison: addStationForComparison,
        removeStationFromComparison: removeStationFromComparison,
        renderHistoryChart: renderHistoryChart,
        renderForecastChart: renderForecastChart,
        renderComparisonChart: renderComparisonChart,
        renderDistributionChart: renderDistributionChart,
        getTimeRange: () => chartConfig.timeRange,
        setTimeRange: (range) => {
            chartConfig.timeRange = range;
            const timeRangeSelect = document.getElementById('time-range');
            if (timeRangeSelect) {
                timeRangeSelect.value = range;
            }
        }
    };
});